<template>
    <div class="home-wrap">
        <el-card class="box-card home-item" shadow="hover" v-for="(item,index) in addressInfoArr" :key="index">
            <div slot="header" class="clearfix" >
                <span>{{ item.defaultAddress === 1 ? '默认收货地址' : '一般收获地址' }}</span>
                <el-button size="small" v-if="item.defaultAddress !== 1"  @click="setDefaultAddress(item.addressId)">设为默认</el-button>

                <el-button style="float: right; padding: 3px 0" type="text" @click="getAddress(item.addressId,index)">管理地址</el-button>
            </div>
            <div class="text">
                <el-descriptions title="" :labelStyle="{fontSize:'20px'}" :column="2">
                    <el-descriptions-item label="姓名">
                        <el-link :underline="false" style="font-size: 20px">{{ item.name }}</el-link>
                    </el-descriptions-item>
                    <el-descriptions-item label="手机号">
                        <el-link :underline="false" style="font-size: 20px">{{ item.phone }}</el-link>
                    </el-descriptions-item>
                    <el-descriptions-item label="地址名称">
                        <el-link :underline="false" style="font-size: 20px">{{ item.addressName }}</el-link>
                    </el-descriptions-item>
                    <el-descriptions-item label="地址类型">
                        <el-link :underline="false" style="font-size: 20px">
                            <el-tag size="small">{{ item.tag | tagToValue}}</el-tag>
                        </el-link>
                    </el-descriptions-item>
                </el-descriptions>
                <el-descriptions title="" :labelStyle="{fontSize:'20px'}" :column="1">
                    <el-descriptions-item label="地址">
                        <el-link :underline="false" style="font-size: 20px">{{ item.province }}</el-link>
                        <el-divider direction="vertical"></el-divider>
                        <el-link :underline="false" style="font-size: 20px">{{ item.city }}</el-link>
                        <el-divider direction="vertical"></el-divider>
                        <el-link :underline="false" style="font-size: 20px">{{ item.region }}</el-link>

                    </el-descriptions-item>
                    <el-descriptions-item label="详细地址" >
                        <el-link :underline="false" style="font-size: 20px">{{ item.detailAddress }}</el-link>
                    </el-descriptions-item>
                </el-descriptions>
                <el-descriptions title="" :labelStyle="{fontSize:'20px'}">
                    <el-descriptions-item label="备注">
                        <el-link :underline="false" style="font-size: 20px">{{ item.describe ? item.describe : '暂无' }}</el-link>
                    </el-descriptions-item>
                </el-descriptions>

            </div>
        </el-card>

        <el-card class="box-card home-item" shadow="hover" style="cursor: pointer;min-height: 311px" @click.native="toAddAddress('add')" v-for="index of 6 - addressInfoArr.length" :key="index + 'e'">
            <div slot="header" class="clearfix">
                <span>待添加</span>
            </div>
            <div class="text" style="text-align: center">
                <el-link :underline="false" style="font-size: 20px">
                    添加地址
                </el-link>
            </div>
        </el-card>


        <el-dialog title="修改地址信息" :visible.sync="addressDialog" :before-close="handleClose" :append-to-body="true" width="40%">
            <div v-loading="loading" element-loading-text="拼命加载中" element-loading-body="true">
                <el-form :model="addressInfoForm" :rules="rules" ref="addressInfoForm" style="width: 80%" label-width="100px">
                    <el-form-item label="姓名" prop="name">
                        <el-input v-model="addressInfoForm.name" placeholder="请输入收货人姓名" prefix-icon="el-icon-user-solid"></el-input>
                    </el-form-item>
                    <el-form-item label="手机号" prop="phone">
                        <el-input v-model="addressInfoForm.phone" placeholder="请输入电话号码" prefix-icon="el-icon-platform-eleme"></el-input>
                    </el-form-item>
                    <el-form-item label="地址名称" prop="addressName">
                        <el-input v-model="addressInfoForm.addressName" placeholder="请输入地址名称" prefix-icon="el-icon-platform-eleme"></el-input>
                    </el-form-item>
                    <el-form-item label="地址类型" prop="tag">
                        <el-radio-group v-model.number="addressInfoForm.tag" size="medium">
                            <el-radio-button label="1" value="1" >家</el-radio-button>
                            <el-radio-button label="2" value="2">学校</el-radio-button>
                            <el-radio-button label="3" value="3">公司</el-radio-button>
                            <el-radio-button label="4" value="">其他</el-radio-button>
                        </el-radio-group>
                    </el-form-item>

                    <el-form-item label="地址" prop="selectedOptions">
                        <el-cascader
                                clearable
                                size="large"
                                :options="options"
                                v-model="addressInfoForm.selectedOptions"
                                @change="handleChange">
                        </el-cascader>
                    </el-form-item>

                    <el-form-item label="详细地址" prop="detailAddress">
                        <el-input v-model="addressInfoForm.detailAddress" placeholder="请输入详细地址" prefix-icon="el-icon-phone-outline"></el-input>
                    </el-form-item>
                    <el-form-item label="备注" prop="describe">
                        <el-input v-model="addressInfoForm.describe" placeholder="备注可以为空" prefix-icon="el-icon-platform-eleme"></el-input>
                    </el-form-item>
                </el-form>
            </div>

            <div slot="footer" class="dialog-footer">
                <el-button @click="addressDialog = false">取 消</el-button>
                <el-button type="primary" @click="submitForm('addressInfoForm')">确 定</el-button>
            </div>
        </el-dialog>

    </div>

</template>

<script>
    import { regionData, CodeToText, TextToCode } from 'element-china-area-data'
    import {getAllAddress, setDefaultAddress, getAddress, addAddress, updateAddress} from "@/api/address";
    export default {
        name: "Address",
        components:{},
        data(){
            return{
                options: regionData,//区域数据

                index: 0,//全局下标
                type: '',//全局操作类型
                loading: true,
                addressDialog: false,
                addressInfoArr: [],
                addressInfoForm: {
                    addressId: '',//地址id
                    addressName: '',//地址名称
                    name: '',//姓名
                    tag: 1,//收货地址类型
                    phone: '',//电话
                    province: '',//省
                    city: '',//市
                    region: '',//区县
                    detailAddress: '',//地址详细信息
                    describe: '',//备注

                    selectedOptions: [],//存放选择的区域代码
                },
                rules: {//修改密码验证规则
                    name: [
                        { required: true, message: '请输入姓名', trigger: 'blur' },
                    ],
                    phone: [
                        { required: true, message: '请输入中国大陆的手机号码', trigger: 'blur' },
                        { pattern: /^1[34578]\d{9}$/, message: '请输入正确的中国大陆的手机号码', trigger: ['blur', 'change']},
                    ],
                    addressName: [
                        { required: true, message: '请输入地址名称', trigger: 'blur' }
                    ],
                    tag: [
                        { required: true, message: '请选择地址类型', trigger: 'change' }
                    ],
                    selectedOptions: [
                        { required: true, message: '请选择收货地址', trigger: 'change' }
                    ],
                    detailAddress: [
                        { required: true, message: '请输入地址', trigger: 'blur' },
                    ],
                }
            }
        },
        methods: {
            handleChange() {//处理地址选择
                console.log(this.addressInfoForm.selectedOptions)
                this.addressInfoForm.province = CodeToText[this.addressInfoForm.selectedOptions[0]];
                this.addressInfoForm.city = CodeToText[this.addressInfoForm.selectedOptions[1]];
                this.addressInfoForm.region = CodeToText[this.addressInfoForm.selectedOptions[2]];
            },
            toAddAddress(type){// 打开增加的弹窗
                Object.keys(this.addressInfoForm).forEach(key => (this.addressInfoForm[key] = ''));//清空表单
                this.loading = false//取消加载
                this.type = type//根据type判断是新增还是修改
                this.addressDialog = true;//打开修改信息的弹窗
            },
            submitForm(formName) {// 新增和修改，根据条件
                if (formName === "addressInfoForm" && this.loading) {
                    //如果是修改信息表单要先查询，等待loading状态结束
                    console.log("还在加载中")
                    return;
                }
                this.$refs[formName].validate((valid) => {
                    if (valid) {
                      if (this.type === "add"){//判断是增加地址还是修改地址
                          this.addAddress()
                      }else{
                          this.updateAddress()
                      }
                    }
                });
            },
            addAddress(){// 新增地址
                console.log(this.addressInfoForm)
                addAddress(this.addressInfoForm).then(response => {
                    console.log(response)
                    if (response.state === true) {
                        //修改视图信息
                        this.addressInfoArr.push(this.addressInfoForm)
                        this.addressDialog = false//关闭表单
                        this.type = ""//重置操作类型
                        this.init()
                        this.$notify.success({title: '成功',message: response.message, duration: 1500});
                    }else{
                        this.$notify.warning({title: '失败',message: response.message, duration: 1500});
                    }
                })
            },
            updateAddress(){// 更新地址
                console.log(this.addressInfoForm)
                updateAddress(this.addressInfoForm).then(response => {
                    console.log(response)
                    if (response.state === true) {
                        //修改视图信息
                        this.addressInfoArr.splice(this.index, 1, this.addressInfoForm)
                        this.addressDialog = false//关闭表单
                        this.$notify.success({title: '成功',message: response.message, duration: 1500});
                    }else{
                        this.$notify.warning({title: '失败',message: response.message, duration: 1500});
                    }
                })
            },
            setDefaultAddress(addressId){// 修改默认地址
                setDefaultAddress(addressId).then(response => {
                    console.log(response)
                    if (response.state === true) {
                        this.init()
                        this.$notify.success({title: '成功',message: response.message, duration: 1500});
                    }else{
                        this.$notify.warning({title: '失败',message: response.message, duration: 1500});
                    }
                })
            },
            getAddress(addressId,index){
                this.addressDialog = true;//打开修改信息的弹窗
                this.loading = true;//进入加载
                this.index = index;
                getAddress(addressId).then((response) => {
                    if (response.state === true) {
                        this.addressInfoForm = response.data.address;//显示信息
                        //地址文字信息，需要转换成代码
                        let array = [response.data.address.province,response.data.address.city,response.data.address.region]
                        let resultArray = []//存储地址代码 文字->代码
                        /*console.log(TextToCode[array[0]].code)
                        console.log(TextToCode[array[0]][array[1]].code)
                        console.log(TextToCode[array[0]][array[1]][array[2]].code)*/
                        resultArray.push(TextToCode[array[0]].code)
                        resultArray.push(TextToCode[array[0]][array[1]].code)
                        resultArray.push(TextToCode[array[0]][array[1]][array[2]].code)

                        this.addressInfoForm.selectedOptions = resultArray
                        this.loading = false;//取消加载
                        this.$notify.success({title: '成功',message: response.message, duration: 1500});
                    }else{
                        this.$notify.warning({title: '失败',message: response.message, duration: 1500});
                    }
                })
            },
            init(){
                getAllAddress().then(response => {
                    console.log(response)
                    if (response.state === true) {
                        this.addressInfoArr = response.data.allAddress;//显示信息
                        //this.$notify.success({title: '成功',message: response.message, duration: 1500});
                    }else{
                        this.$notify.warning({title: '失败',message: response.message, duration: 1500});
                    }
                })
            },
            handleClose(done) {
                this.$confirm('确认关闭？').then(_ => {done();}).catch(_ => {});},
        },
        filters: {
            tagToValue(tag){
                switch (tag) {
                    case 1 : return "家"
                    case 2 : return "学校"
                    case 3 : return "公司"
                    case 4 : return "其他"
                    default : return "其他"
                }
            }
        },
        beforeMount(){
            this.init()
        },
    }
</script>

<style scoped>
    .home-wrap{
        width: 70vw;
        margin: 0 auto;
        display: flex;
        flex-direction: row;
        justify-content: space-between;
        flex-wrap: wrap;
    }
    .home-item{
        margin: 0 20px 20px 20px;
    }
    .todolist{
        width: fit-content;
        height: 500px;
    }
    .todolist .el-card__body{

    }

    .box-card{
        width: calc(50% - 40px);
        height: fit-content;
    }

    .text {
        font-size: 14px;
    }
    /*卡片头部字体*/
    .el-card__header span{
        padding: 18px 20px;
        font-weight: 600;
    }

    .clearfix:before,
    .clearfix:after {
        display: table;
        content: "";
    }
    .clearfix:after {
        clear: both
    }

    @media (max-width: 1200px){
        .box-card{
        }
        .home-wrap{
            flex-direction: column;
            align-items: center;
        }
    }
</style>
